<template>
  <!-- 导出-->
  <div class="export-dixed-wrap">
    <div class="export-header flex-c">
      <span>导出文件名：</span>
      <a-input v-model="fileName" style="width: 200px" placeholder="请输入文件名名" />
      <template v-if="supportTemplate">
        <span style="margin-left: 40px">导出模板：</span>
        <a-select v-model="currentTemp" style="width: 200px" value-key="id" @change="changeTemplate">
          <a-option v-for="(item, i) in templateList" :key="i" :value="item" :label="item.templateName" />
        </a-select>
      </template>
    </div>
    <div class="field-handle-w">
      <div class="field-list-w">
        <div class="header flex-c">
          <h3>所有字段</h3>
          <a-checkbox label="全选/清空" @change="handleCheckAll">全选</a-checkbox>
        </div>
        <ul>
          <li v-for="(item, index) in fieldList" :key="index">
            <p class="title">{{ item.group }}</p>
            <div class="filed-con">
              <a-checkbox v-for="(field, j) in item.columns" :key="j" :disabled="field.disabled" v-model="field.checked" @change="handleCheckedModel($event, field)">
                <span> {{ field.name }}</span>
                <a-popover v-if="field.tip" :content="field.tip">
                  <icon-question-circle />
                </a-popover>
              </a-checkbox>
            </div>
          </li>
        </ul>
      </div>
      <div class="excel-fieid-sort">
        <div class="header flex-c">
          <h3>EXCEL导出的字段顺序</h3>
          <p style="color: #999; font-weight: normal">鼠标拖动进行排序</p>
        </div>
        <div class="list-w">
          <draggable :list="checkFieldList" item-key="key" animation="300">
            <template #item="{ element }">
              <a-tag style="margin: 0 10px 10px 0" closable @close="delExcelField(element)">{{ element.name }}</a-tag>
            </template>
          </draggable>
          <p v-if="checkFieldList.length <= 0" class="no-field">暂无导出字段，请勾选需要导出的字段</p>
        </div>
      </div>
    </div>
    <div class="footer-handle-btn">
      <a-button type="primary" :loading="isExportLoad" @click="exportExcel">{{ isExportLoad ? '加载中' : '导出Excel表格' }}</a-button>
      <a-dropdown v-if="supportTemplate">
        <a-button style="margin-left: 20px">保存为模板 <icon-down /></a-button>
        <template #content>
          <a-doption v-if="currentTemp && currentTemp.templateName" @click.stop="uplateTemplate">覆盖当前模板</a-doption>
          <a-doption @click.stop="openCreateTempDialog">另存新模板</a-doption>
        </template>
      </a-dropdown>
    </div>
    <a-modal v-model:visible="showCreateTempDialog" width="400px" :on-before-ok="createTemplate" title="请输入模板名称" title-align="start" :mask-closable="false" :ok-loading="createTemplateLoading" @cancel="tempEditName = ''">
      <a-input v-model="tempEditName" />
    </a-modal>
    <a-modal v-model:visible="openDownLoadTitle" width="400px" :footer="false" title="提示" title-align="start" :mask-closable="false">
      <div style="text-align: center">
        <p class="text-c" style="font-size: 16px">您的导出任务已发起，稍后前往下载中心下载</p>
        <a-button style="margin-top: 20px" type="primary" status="success" @click="toDownLoad">前往下载中心</a-button>
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, computed, inject } from 'vue'
  import * as ExportApi from '@/api/export'
  import { parseJson } from '@/utils'
  import draggable from 'vuedraggable'
  import { Message } from '@arco-design/web-vue'
  import { filterData } from '@/utils'
  import { useRouter } from 'vue-router'

  const props = defineProps({
    tabName: {
      //多文件tab切换名字
      type: String,
    },
    supportAll: {
      //是否支持选择全部
      type: Boolean,
      default: false,
    },
    supportTemplate: {
      //是否支持保存模板
      type: Boolean,
      default: false,
    },
    templateType: {
      //模板类型
      type: String,
      default: 'EXPORT_TEMPLATE',
    },
    exportApi: {
      //导出API
      type: String,
    },
    seachData: {
      //查询条件
      type: Object,
      default: () => {},
    },
    checkedList: {
      //选中数据
      type: Array,
      default: () => [],
    },
    excelName: {
      //导出文件名字
      type: String,
    },
    fieldList: {
      //表头字段
      type: Array,
      default: () => [],
    },
  })
  onMounted(() => {
    getData()
  })

  const enableFixedList = computed(() => {
    let list: Array<any> = []
    fieldList.value.forEach((item) => {
      item.columns.forEach((column: any) => {
        if (!column.disabled) list.push(column)
      })
    })
    return list
  })
  const fromLocation: any = inject('fromLocation')
  const router = useRouter()
  const fileName = ref(props.excelName)
  const currentTemp = ref<any>()
  const templateList = ref<Array<any>>([])
  const fieldList = ref<Array<any>>([])
  const checkFieldList = ref<Array<any>>([])
  const isExportLoad = ref(false)
  const showCreateTempDialog = ref(false)
  const tempEditName = ref('')
  const createTemplateLoading = ref(false)
  const openDownLoadTitle = ref(false)

  // 获取相关数据
  async function getData() {
    // 获取定义的所有表头
    fieldList.value = JSON.parse(JSON.stringify(props.fieldList || []))
    if (!props.supportTemplate) {
      setDefaultData()
      return
    }
    // 支持模板的时候需要先获取模板
    await getTemplateList()

    if (templateList.value?.length) {
      currentTemp.value = templateList.value[0]
      changeTemplate()
    } else {
      setDefaultData()
    }
  }
  // 设置默认表头
  function setDefaultData() {
    checkFieldList.value = enableFixedList.value.filter((el: any) => el.checked)
  }

  //根据选中导出字段的变动，更改所有表头的选中状态
  async function setDftColumn() {
    let defauleData = [...checkFieldList.value]
    if (!defauleData.length) return
    fieldList.value.map((item: any) => {
      item.columns.forEach((column: any) => {
        let exitItem = checkFieldList.value.find((list) => column.key == list.key)
        column.checked = exitItem ? true : false
      })
    })
  }
  //全选
  function handleCheckAll(val: any) {
    if (!val) {
      checkFieldList.value = []
    } else {
      checkFieldList.value = JSON.parse(JSON.stringify(enableFixedList.value))
    }
    fieldList.value.forEach((item: any) => {
      item.columns.forEach((list: any) => {
        if (!list.disabled) {
          list.checked = val
        }
      })
    })
  }
  // 选中单个
  function handleCheckedModel(val: any, field: any) {
    if (val) return checkFieldList.value.push(field)
    let _key = field.key
    let _index = checkFieldList.value.findIndex((item) => item.key == _key)
    if (_index > -1) {
      checkFieldList.value.splice(_index, 1)
    }
  }
  //删除选中的导出字段
  function delExcelField(row: any) {
    let _index = checkFieldList.value.findIndex((el: any) => el.key === row.key)
    checkFieldList.value.splice(_index, 1)
    fieldList.value.forEach((item: any) => {
      item.columns.forEach((list: any) => {
        if (list.key === row.key) {
          list.checked = false
        }
      })
    })
  }

  //获取导出模板
  async function getTemplateList() {
    const res: any = await ExportApi.findTemplateList({ templateCode: props.templateType })
    templateList.value = res?.data || []
  }
  // 保存模板
  async function createTemplate() {
    if (!tempEditName.value) {
      Message.error('请输入模板名称！')
      return false
    }

    const res: any = await ExportApi.createTemplate({
      enable: true,
      templateCode: props.templateType,
      templateName: tempEditName.value,
      templateContent: JSON.stringify(checkFieldList.value),
      templateType: 1,
    })
    if (!res) return false
    Message.success('模板创建成功')
    showCreateTempDialog.value = false
    tempEditName.value = ''
    getTemplateList()
  }

  //切换模板
  function changeTemplate() {
    checkFieldList.value = parseJson(currentTemp.value.templateContent, [])
    setDftColumn()
  }
  // 切换模板
  async function uplateTemplate() {
    const res: any = await ExportApi.updateTemplate({
      templateType: 1,
      templateCode: props.templateType,
      id: currentTemp.value.id,
      templateContent: JSON.stringify(checkFieldList.value),
    })
    if (res) {
      Message.success('覆盖当前模板成功！')
      getTemplateList()
    }
  }
  function openCreateTempDialog() {
    if (!checkFieldList.value.length) {
      Message.error('请选择需要导出的字段')
      return
    }
    showCreateTempDialog.value = true
  }
  // 前往下载中心；
  function toDownLoad() {
    openDownLoadTitle.value = false
    router.push('/system/download/download')
  }
  // 导出
  async function exportExcel() {
    if (!props.exportApi) return
    let columnList: any = getExportLabel()
    if (!columnList?.length) {
      Message.error('请选择需要导出的字段')
      return
    }
    let searchVal = filterData(props.seachData, true, true)
    delete searchVal.pageNum
    delete searchVal.pageSize

    isExportLoad.value = true
    let _params = {
      fileName: (fileName.value || props.excelName) + '.xls',
      idList: props.checkedList,
      queryParam: searchVal,
      columnList: columnList,
      fromLocation: fromLocation,
    }
    const res: any = await ExportApi[props.exportApi](_params)
    isExportLoad.value = false
    if (res) {
      openDownLoadTitle.value = true
    }
  }
  // 设置表头
  function getExportLabel() {
    let columnList: Array<any> = [] //导出所有表头
    checkFieldList.value.forEach((check: any) => {
      let _pu = { key: check.key, name: check.name, keyType: check.keyType }
      if (!check.parentLevel) {
        //非二级表头
        columnList.push(_pu)
      } else {
        let _index = columnList.findIndex((col) => col.name == check.parentLevel)
        if (_index > -1) {
          columnList[_index].itemList.push(_pu)
        } else {
          //未存在 创建一个push进去
          let _puWarp = {
            key: 'leve' + check.parentLevel,
            name: check.parentLevel,
            itemList: [_pu],
          }
          columnList.push(_puWarp)
        }
      }
    })
    if (!columnList.find((el) => el.key == 'sort')) {
      let addIndex = [{ name: '序号', key: 'sort', keyType: '1' }]
      columnList = [...addIndex, ...columnList]
    }
    return columnList
  }
</script>
<style lang="less" scoped>
  .export-dixed-wrap {
    height: 100%;
    display: flex;
    flex-direction: column;
    .footer-handle-btn {
      text-align: right;
    }
  }
  .export-header {
    margin: 10px 0;
  }
  .header {
    width: 100%;
    display: flex;
    align-items: center;
    background-color: #f7f8fa;
    padding: 5px 10px;
    font-weight: bold;
    border-bottom: 1px solid #dde2ee;
    h3 {
      font-size: 14px;
      margin-right: 20px;
    }
  }
  .field-handle-w {
    flex: 1;
    overflow: auto;
    .field-list-w {
      margin-bottom: 10px;
      border: 1px solid #dde2ee;
      ul {
        padding: 10px;
        li {
          margin-bottom: 10px;
          &:last-child {
            margin-bottom: 0;
          }
          .title {
            font-size: 14px;
            font-weight: bold;
          }
          .filed-con {
            .arco-checkbox {
              width: 140px;
              padding: 4px 6px 4px;
            }
          }
        }
      }
    }
  }
  .excel-fieid-sort {
    border: 1px solid #dde2ee;
    .list-w {
      padding: 10px;
    }
  }
</style>
